package com.dsc;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author: Du Shun Chang
 * @title: CookieServlet
 * @date: 2022/2/8 14:57
 * @description: TODO
 * @version：1.0
 */
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        /*服务器端获取客户端cookie*/
        Cookie[] cookies = req.getCookies();
        PrintWriter printWriter = resp.getWriter();
        Date date = new Date();
        long LastLoginTime;

        /*判断cookie是否存在*/
        if (cookies != null) {
            printWriter.write("你上一次访问遇见小Du说的时间是：");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("LastLoginTime")) {
                    LastLoginTime = Long.parseLong(cookie.getValue());
                    date.setTime(LastLoginTime);
                    printWriter.write(date.toLocaleString());
                }
            }
        } else {
            printWriter.write("这是您第一次访问小Du猿：" );
            printWriter.write(date.toLocaleString());
        }
        /*服务器给客户端响应一个cookie*/
        Cookie cookie = new Cookie("LastLoginTime", String.valueOf(System.currentTimeMillis()));
        /*设置cookie的有效期*/
        cookie.setMaxAge(60);
        /*服务端响应给客户端cookie*/
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}
